package org.chinacloud.wanghui.jdownload;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * Created with IntelliJ IDEA.
 * User: wanghui
 * Date: 13-10-30
 * Time: 下午2:58
 * To change this template use File | Settings | File Templates.
 */
public class DownloadsTableModel extends AbstractTableModel implements Observer {

    private static final String[] columnNames = {"地址","大小","进度","状态"};
    private static final Class[] columnClass =
            {String.class,String.class,JProgressBar.class,String.class};
    private List<Download> downloadList = new ArrayList<Download>();
    public void addDownload(Download download){
        download.addObserver(this);
        downloadList.add(download);
        fireTableRowsInserted(getRowCount() - 1,getRowCount() - 1);
    }


    public Download getDownload(int row){
        return downloadList.get(row);
    }

    public void clearDownload(int row){
        downloadList.remove(row);
        fireTableRowsDeleted(row,row);
    }

    public int getColumnCount(){
        return columnNames.length;
    }
    public String getColumnName(int col){
        return columnNames[col];
    }
    public int getRowCount(){
        return downloadList.size();
    }


    public Object getValueAt(int row,int col){
        Download download = downloadList.get(row);
        switch (col){
            case 0:
                return download.getUrl();
            case 1:
                int size = download.getSize();
                return (size == -1) ? "" : Integer.toString(size);
            case 2:
                return new Float(download.getProgress());
            case 3:
                return download.getStatus();
        }
        return "";
    }


    public void update(Observable o, Object arg){
        int index = downloadList.indexOf(o);
        fireTableRowsUpdated(index,index);
    }


}
